var express = require('express');
var router = express.Router();
var fetch = require("fetch").fetchUrl
var { $rq } = require("../util/rq")
let result = require("../util/result.js")
// console.log(fetch)

/* GET base page. */
router.get('/', function(req, res, next) {
    res.render('base', { title: 'baseApi', 
        apiList:[
            {
                url:"base/getAccessToken(请求第三方Api，获取access_token)",
                method:"GET",
                params:{
                    key:"grant_type",
                    appid:"小程序appid",
                    secret: "小程序密钥"
                },
                result:{
                    "success": true,
                    "data":"{"
                        +"access_token"+":"+"23_w0OtD1X72LIQo4dwctVsp99kjtIRRk9Gw5bx7UOglotfL7k9LqB1gKbZw86CNht6cnCv9oKBcFEcPg5u4seXN0hJMSEocsbun2dQxCTyZarP06YcToVbdP-MOLc7o7EhMSzqR4URT__BdZc-NMLbAIARQP,"
                        +"expires_in"+":"+7200
                    +"}"
                }
            },
            {
                url:"base/getdatabase(获取指定云环境集合信息)",
                method:"post",
                params:{
                    env:"云开发数据库环境id",
                    limit:"获取数量限制,默认10",
                    offset:"偏移量,默认0"
                },
                result:{
                    "success": true,
                    "data":`{
                        {
                        "errcode": 0,
                        "errmsg": "ok",
                        "collections": [
                            {
                                "name": "geo",
                                "count": 13,
                                "size": 2469,
                                "index_count": 1,
                                "index_size": 36864
                            },
                            {
                                "name": "test_collection",
                                "count": 1,
                                "size": 67,
                                "index_count": 1,
                                "index_size": 16384
                            }
                        ],
                        "pager": {
                            "Offset": 0,
                            "Limit": 10,
                            "Total": 2
                        }
                      }
                    }`
                }
            }
        ]
    });
});
router.get('/getAccessToken', function(req, res, next) { // 请求第三方Api，获取access_token
    let urlParam = {
        grant_type:"client_credential",
        appid: req.query.appid?req.query.appid:"wx77a955e951e5ebe3",
        secret: req.query.secret?req.query.secret:"ee82b0d22c015bc2ac0407c588803423"
    };
    // fetch("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx77a955e951e5ebe3&secret=ee82b0d22c015bc2ac0407c588803423",{
    //     method:"GET",
    //     body: JSON.stringify({
    //         grant_type:"client_credential",
    //         appid:"wx77a955e951e5ebe3",
    //         secret:"ee82b0d22c015bc2ac0407c588803423"
    //     })
    // },function(error, meta, body){
    //     console.log(error)
    //     console.log(meta)
    //     console.log(body.toString());
    // })
    $rq.get("cgi-bin/token",urlParam).then(response=>{
        global.TOKEN_INFO = response
        let r =  result.createResult(true, response);
        res.json(r);
    }).catch(err=>{
        let r =  result.createResult(false, err);
        res.json(r);
        console.log(err)
    })
});

router.get('/getdatabase', function(req, res, next) { // 获取指定云环境集合信息
    let urlParam = {
        // access_token: req.query.access_token?req.query.access_token:"",
        env: req.query.env?req.query.env:"test-3b6a08",
        limit: req.query.limit?req.query.limit:10,
        offset: req.query.offset?req.query.offset:0
    };
    $rq.post("tcb/databasecollectionget?access_token="+global.TOKEN_INFO.access_token,urlParam).then(response=>{
        let r =  result.createResult(true, response);
        res.json(r);
    }).catch(err=>{
        let r =  result.createResult(false, err);
        res.json(r);
        // console.log(err)
    })
});

// https://api.weixin.qq.com/tcb/databasequery?access_token=ACCESS_TOKEN
router.get('/getVitaeList', (req, res, next) => { // 获取简历列表
    let urlParam = {
        env: req.query.env?req.query.env:"test-3b6a08",
        query: 'db.collection(\"vidta_list\").where({userId: "ovn770AKbvip0n7FEqgDzb6ytsHE",}).limit(10).skip(1).get()'
    }
    $rq.post("tcb/databasequery?access_token="+global.TOKEN_INFO.access_token,urlParam).then(response=>{
        let r =  result.createResult(true, response);
        res.json(r);
    }).catch(err=>{
        let r =  result.createResult(false, err);
        res.json(r);
        // console.log(err)
    })
})


// https://api.weixin.qq.com/tcb/invokecloudfunction?access_token=ACCESS_TOKEN&env=ENV&name=FUNCTION_NAME
router.get('/getVitaeDetail', function(req, res, next) { // 触发云函数获取响应数据
    console.log(req.query,'getVitaeDetail')
    let urlParam = {
        POSTBODY: {
            "vidtaName": req.query.vidtaName,
            "creatTime": req.query.creatTime,
            "template": req.query.template,
            "theme": req.query.theme,
            "customModal": req.query.customModal,
            "baseInfoId":req.query.baseInfoId, 
            "jobIntentionId":req.query.jobIntentionId, 
            "workListId":req.query.workListId, 
            "educationId":req.query.educationId, 
            "projectId":req.query.projectId, 
            "skillTreeId":req.query.skillTreeId, 
            "addedTagId":req.query.addedTagId, 
            "evauationId":req.query.evauationId,
        }
    }
    $rq.post("tcb/invokecloudfunction?access_token="+global.TOKEN_INFO.access_token+"&env=test-3b6a08&name=getVidtaDetail",urlParam).then(response=>{
        let r =  result.createResult(true, response);
        res.json(r);
    }).catch(err=>{
        let r =  result.createResult(false, err);
        res.json(r);
        // console.log(err)
    })
})

module.exports = router;